import {Polygon} from 'ol/geom'
import TileLayer from 'ol/layer/Tile'
import ImageLayer from 'ol/layer/Image'
import ImageWMS from 'ol/source/ImageWMS'
import TileWMS from 'ol/source/TileWMS'
import {DragBox, Select} from 'ol/interaction'
import {click, platformModifierKeyOnly} from 'ol/events/condition'
import {Fill, Icon, Stroke, Style, Text} from 'ol/style'
import { equalTo, or } from 'ol/format/filter'
import {WFS, GeoJSON} from 'ol/format'
import store from '@/store'

class TyHelper {
  constructor(option) {
    // const mapOption = option.map.option
    this.map = option.map
    this.resolutions = [
      0.014871631286439252,
        0.007994988979589742,
        0.0029743262572878505,
        0.0014276766034981682,
        7.138383017490841E-4,
        3.5691915087454206E-4,
        1.7845957543727103E-4,
        9.517844023321122E-5,
        4.758922011660561E-5,
        2.3794610058302804E-5,
        1.1897305029151402E-5,
        7.138383017490841E-6
    ]
    this.projection = 'EPSG:4326'
    this.extent = [118.02785601698666, 43.36606061645537, 136.79103352179985, 55.6497932864995]
    this.prefix = 'map'
    this.repairLevel = 12 - this.resolutions.length
    this.geoServerUrl =  null
    this.geoWorkSpace =  null
    this.partOverlaysList = []
    // 事件交互对象数组
    this.interactionCollection = []
    this.wmsLayers = []
    this.layers = [{
      id: 'district',
      type: 'T_MAP_DISTRICT_GRID',
      styles: 'area_grid',
      layerName: `${this.prefix}:area_grid_sys`, // 区域网格
      maxResolution: 9 - this.repairLevel,
      mixResolution: this.resolutions.length,
      zoom: 11 - this.repairLevel
    }, {
      id: 'street',
      type: 'T_MAP_STREET_GRID',
      styles: 'area_grid',
      layerName: `${this.prefix}:area_grid_sys`, // 街道网格
      maxResolution: 10 - this.repairLevel,
      mixResolution: 13 - this.repairLevel,
      zoom: 11 - this.repairLevel
    }, {
      id: 'comm',
      type: 'T_MAP_COMM_GRID',
      styles: 'area_grid',
      layerName: `${this.prefix}:area_grid_sys`, // 社区网格
      maxResolution: 11 - this.repairLevel,
      mixResolution: 15 - this.repairLevel,
      zoom: 12 - this.repairLevel
    }, {
      id: 'unit',
      type: 'T_MAP_UNIT_GRID',
      styles: 'area_grid',
      layerName: `${this.prefix}:area_grid_sys`, // 单元网格
      maxResolution: 14 - this.repairLevel,
      mixResolution: this.resolutions.length,
      zoom: 15 - this.repairLevel
    }, {
      id: 'work',
      type: null,
      styles: 'work_grid',
      layerName: `${this.prefix}:work_grid_sys`, // 工作网格
      maxResolution: 13 - this.repairLevel,
      mixResolution: 14 - this.repairLevel,
      zoom: 14 - this.repairLevel
    }, {
      id: 'duty',
      type: null,
      styles: 'duty_grid',
      layerName: `${this.prefix}:duty_grid_sys`, // 责任单位网格
      maxResolution: 11 - this.repairLevel,
      mixResolution: 15 - this.repairLevel,
      zoom: 12 - this.repairLevel
    }, {
      id: 'area_grid',
      type: null,
      styles: '',
      layerName: `${this.prefix}:area_grid_sys`, // 区域网格
      zoom: 15 - this.repairLevel
    }, {
      id: 'area_work',
      type: null,
      layerName: `${this.prefix}:area_work_grid_sys`, // 区域网格加工作网格
      zoom: 14 - this.repairLevel
    }, {
      id: 'wh_parts',
      type: null,
      styles: '',
      layerName: `${this.prefix}:wh_sys` // 部件
    }, {
      id: 'wh_area_group',
      type: null,
      styles: '',
      layerName: `${this.prefix}:area_grid_group_sys`, // 区域部件
      mixResolution: 13 - this.repairLevel
    }, {
      id: 'mph_poi_road',
      type: null,
      layerName: `${this.prefix}:mph_poi_road_sys`, // 兴趣点门牌号道路
      zoom: 15 - this.repairLevel
    }, {
      id: 'car_fence',
      type: null,
      layerName: `${this.prefix}:car_electronic_fence`, // 车辆电子围栏
      zoom: 15 - this.repairLevel
    }]
    this.basicParams = {
      SERVICE: 'WMS',
      VERSION: '1.1.1',
      REQUEST: 'GetFeatureInfo',
      FORMAT: 'JSON',
      TRANSPARENT: true,
      exceptions: 'application/vnd.ogc.se_inimage',
      INFO_FORMAT: 'application/json',
      FEATURE_COUNT: 10000,
      X: 50,
      Y: 50,
      STYLES: '',
      WIDTH: '101',
      HEIGHT: '101'
    }
  }

  /**
   * @Description 初始化WMS图层
   * @Date 2019/12/27 17:42
   * @Author yuesheng.zhu@topevery.club
   */
   initWMSLayer(layerId, flag = false, cql_filter = '', styles, is_remove = false) {
   // console.log('layerId-----------', layerId)
  //   if (layerId === undefined) return
  //   if (layerId.includes('wh_parts_')) {
  //     if ((this.wmsLayers.findIndex((layer) => { return layer.id === layerId })) !== -1) return
  //   }
  //   const layer = this.getLayer(layerId)
  //   styles = validatenull(styles) ? (validatenull(layer.styles) ? '' : `${this.prefix}:${layer.styles}`) : styles
  //   cql_filter = cql_filter === '' ? (layer.type === null ? null : `"properties.type"='${layer.type}'`) : cql_filter
  //   if (is_remove) this.removePartLayer(layer.id)
  //   if (flag) {
  //     const wmsLayer = this.createWMSLayer(layer, cql_filter, styles)
  //     this.addLayer(wmsLayer.untiled)
  //     this.addLayer(wmsLayer.tiled)
  //     this.wmsLayers.push({
  //       id: layer.id,
  //       layerName: layer.layerName,
  //       untiled: wmsLayer.untiled,
  //       tiled: wmsLayer.tiled
  //     })
  //     if (layer.zoom) {
  //       if (this.map.getView().getZoom() < layer.zoom) this.zoomTo(layer.zoom)
  //     }
  //     console.log('this.map.getMap().getLayers()', this.map.getLayers())
  //   } else {
  //     this.removePartLayer(layer.id)
  //   }
   }

  /**
   * @Description 创建WMS图层
   * @Date 2019/12/27 17:42
   * @Author yuesheng.zhu@topevery.club
   */
  createWMSLayer(layer, cql_filter, styles) {
    const format = 'image/png'
    const untiled = new ImageLayer({
      source: new ImageWMS({
        ratio: 1,
        url: this.geoServerUrl,
        params: {
          FORMAT: format,
          VERSION: '1.1.1',
          STYLES: styles,
          LAYERS: layer.layerName,
          TRANSPARENT: true,
          CQL_FILTER: cql_filter
        }
      })
    })
    if (layer.maxResolution) untiled.setMaxResolution(this.resolutions[layer.maxResolution])
    if (layer.minResolution) untiled.setMinResolution(this.resolutions[layer.minResolution])
    untiled.setZIndex(layer.zIndex || 1)
    const tiled = new TileLayer({
      visible: false,
      source: new TileWMS({
        url: this.geoServerUrl,
        params: {
          FORMAT: format,
          VERSION: '1.1.1',
          tiled: true,
          STYLES: styles,
          LAYERS: layer.layerName,
          TRANSPARENT: true,
          CQL_FILTER: cql_filter
        }
      })
    })
    if (layer.maxResolution) tiled.setMaxResolution(this.resolutions[layer.maxResolution])
    if (layer.minResolution) tiled.setMinResolution(this.resolutions[layer.minResolution])
    tiled.setZIndex(layer.zIndex || 1)
    return {untiled: untiled, tiled: tiled}
  }

  /**
   * @Description 添加部件图层
   * @Date 2019/12/27 17:50
   * @Author yuesheng.zhu@topevery.club
   */
  addPartsLayers(partsType, zIndex = 100) {
    this.layers.push({
      id: `wh_parts_${partsType}`,
      type: null,
      styles: partsType,
      layerName: `${this.prefix}:wh_sys`, // 部件
      // maxResolution: 13 - this.repairLevel,
      // mixResolution: 14 - this.repairLevel,
      // zoom: 14 - this.repairLevel,
      zIndex: zIndex
    })
  }

  /**
   * @Author yuesheng.zhu@topevery.club
   * @Date 2019/5/9 11:44
   * @Description geoserver 根据坐标点图层查询
   */
  // async searchGeoFeature(layerId, coordinate, cqlFilterLayer) {
  //   const layer = this.getLayer(layerId)
  //   let cqlFilter = coordinate === null ? '' : `contains(geometry,point(${coordinate[0]} ${coordinate[1]}))`
  //   /* if (isAppointLayer === undefined || isAppointLayer) {
  //      cqlFilter += ` and "properties.type" like '${layer.type}'`
  //    }*/
  //   if (cqlFilterLayer) {
  //     cqlFilter += ` ${coordinate === '' ? '' : 'or'} ${cqlFilterLayer}`
  //   }
  //   const source = new TileWMS({
  //     url: this.geoServerUrl,
  //     serverType: 'geoserver',
  //     crossOrigin: 'anonymous',
  //     params: {
  //       FORMAT: 'JSON',
  //       VERSION: '1.1.1',
  //       QUERY_LAYERS: layer.layerName,
  //       LAYERS: layer.layerName,
  //       TRANSPARENT: true,
  //       CQL_FILTER: cqlFilter
  //     }
  //   })
  //   const url = source.getFeatureInfoUrl(
  //     coordinate,
  //     this.map.getView().getResolution(),
  //     this.map.getView().getProjection(),
  //     {
  //       INFO_FORMAT: 'application/json',
  //       FEATURE_COUNT: 50
  //     }
  //   )
  //   return await http.$GET(url.substr(url.indexOf('geoServerApi'), url.length))
  // }

  /**
   * @Description 根据参数图层查询
   * @Date 2020/1/3 15:55
   * @Author yuesheng.zhu@topevery.club
   */
  // async mapGeoFeature(layerId, cqlFilterLayer, extent) {
  //   // console.log('this.map.getView().getProjection()', this.map.getView().calculateExtent(this.map.getSize()))
  //   const layer = this.getLayer(layerId)
  //   const params = Object.assign({}, this.basicParams,
  //     {
  //       SRS: this.projection,
  //       BBOX: (extent || this.extent).join(','),
  //       // BBOX: this.map.getView().getProjection().join(','),
  //       LAYERS: layer.layerName,
  //       QUERY_LAYERS: layer.layerName
  //     })
  //   if (!validatenull(cqlFilterLayer)) {
  //     params['CQL_FILTER'] = cqlFilterLayer
  //   }
  //   return await http.$GET(this.geoServerUrl.substr(this.geoServerUrl.indexOf('geoServerApi'), this.geoServerUrl.length), params)
  // }

  /**
   * @Description 根据范围查询要素数据
   * @Date 2020/1/3 15:55
   * @Author yuesheng.zhu@topevery.club
   */
  searchWFSFeature(layerId, filters, extent, callback) {
    const params = []
    let doFilter = null
    filters.map(filter => {
      params.push(equalTo(Object.keys(filter), filter[Object.keys(filter)]))
    })
    if (filters.length === 1) {
      doFilter = params[0]
    } else {
      doFilter = or(...params)
    }
    const layer = this.getLayer(layerId)
    const featureRequest = new WFS().writeGetFeature({
      srsName: this.map.getView().getProjection().getCode(),
      geometryName: 'geometry',
      bbox: extent,
      featureTypes: [layer.layerName],
      outputFormat: 'application/json',
      filter: doFilter
    })
    const url = this.geoServerUrl.substr(this.geoServerUrl.indexOf('geoServerApi'), this.geoServerUrl.length)
    fetch(`${process.env.VUE_APP_API}${url}/wfs`, {
      method: 'POST',
      body: new XMLSerializer().serializeToString(featureRequest)
    }).then((response) => {
      return response.json()
    }).then((json) => {
      const features = new GeoJSON().readFeatures(json)
      if (callback) {
        callback(features)
      }
    })
  }

  getMap() {
    return this.map
  }

  getMapView() {
    return this.getMap().getView()
  }

  getLayer(layerId) {
    for (const index in this.layers) {
      if (this.layers[index].id === layerId) {
        return this.layers[index]
      }
    }
  }

  getLayerName(layerId) {
    for (const index in this.layers) {
      if (this.layers[index].id === layerId) {
        return this.layers[index].layerName
      }
    }
  }

  getPartLayer(partLayerId) {
    for (const index in this.wmsLayers) {
      if (this.wmsLayers[index].id === partLayerId) {
        return this.wmsLayers[index]
      }
    }
    return null
  }

  removePartLayer(partLayerId) {
    const partLayer = this.getPartLayer(partLayerId)
    if (partLayer) {
      this.removeLayer(partLayer.untiled)
      this.removeLayer(partLayer.tiled)
      this.wmsLayers.splice(this.wmsLayers.findIndex(item => item === partLayer), 1)
    }
  }

  clearPartLayers() {
    for (const index in this.wmsLayers) {
      this.removeLayer(this.wmsLayers[index].layer)
    }
    this.wmsLayers.splice(0, this.wmsLayers.length)
  }

  addLayer(layer) {
    this.map.addLayer(layer)
  }
  removeLayer(layer) {
    this.map.removeLayer(layer)
  }

  getLayerStyle(opacity, text, zIndex,gridType) {
    if (!opacity) {
      opacity = 1
    }
    const colors = [
      [121, 170, 208],
      [26, 188, 156],
      [155, 89, 182],
      [192, 57, 43],
      [120, 186, 0],
      [255, 255, 132],
      [0, 132, 0],
      [255, 0, 0],
      [0, 0, 255],
      [255, 132, 198]
    ]
    const index = Math.round(Math.random() * 9)
    const strokeColor = 'rgb(255,0,0)'
    let fillColor = 'rgba(' + colors[9 - index].join() + ',' + opacity + ')'
    if(gridType === 1){
      fillColor = 'rgb(0 0 0 / 0)'
    }
    const randomStyle = new Style({
      stroke: new Stroke({
        color: strokeColor,
        width: 2
      }),
      fill: new Fill({
        color: fillColor
      }),
      text: new Text({ // 文本样式
        font: '14px Microsoft YaHei',
        fill: new Fill({
          color: '#000'
        }),
        stroke: new Stroke({
          color: '#fff',
          width: 3
        }),
        text: text,
        textAlign: 'center'
      })
    })
    // if (!validatenull(text)) {
    //   randomStyle.setText(
    //     new Text({ // 文本样式
    //       font: '14px Microsoft YaHei',
    //       fill: new Fill({
    //         color: '#000'
    //       }),
    //       stroke: new Stroke({
    //         color: '#fff',
    //         width: 3
    //       }),
    //       text: text,
    //       textAlign: 'center'
    //     })
    //   )
    // }
    if (zIndex) {
      randomStyle.setZIndex(zIndex)
    }
    return randomStyle
  }

  getImageStyle(options, index = 1) {
    const imgScale = options.imgScale || 0.9
    const icon = options.icon || './image/map/loc-red.png'
    const styles = []
    styles.push(
      new Style({
        image: new Icon({
          src: icon,
          scale: imgScale
        }),
        zIndex: index
      })
    )
    return styles
  }

  //
  zoomTo(level) {
    this.map.getView().setZoom(level)
  }
  //
  getZoom() {
    return this.map.getView().getZoom()
  }

  setViewport(points) {
    const polygon = new Polygon([points])
    this.map.getView().fit(polygon, this.map.getSize())
  }

  // 创建矢量图层
  /* MapTuYuanHelper.prototype.createVectorLayer = function(opt) {
    return new VectorLayer(opt)
  }*/

  // 事件注册 begin
  selectInteraction(opt) {
    let defaultOpt = {
      condition: click
    }
    if (opt && opt instanceof Object) {
      defaultOpt = Object.assign(defaultOpt, opt)
    }
    const currInteraction = new Select(defaultOpt)
    this.map.addInteraction(currInteraction)
    // 当存在回调函数的时候，才注册事件
    if (defaultOpt && typeof defaultOpt.eventHandler === 'function') {
      currInteraction.on('select', (e) => {
        defaultOpt.eventHandler(e)
      })
    }
    return currInteraction
  }

  dragBoxInteraction = function(option) {
    let defaultOpt = {
      condition: platformModifierKeyOnly
    }
    if (option && option instanceof Object) {
      defaultOpt = Object.assign(defaultOpt, option)
    }
    const currInteraction = new DragBox(defaultOpt)
    this.map.addInteraction(currInteraction)
    currInteraction.on('boxstart', () => {
      if (defaultOpt && typeof defaultOpt.startDragBoxHandler === 'function') {
        defaultOpt.startDragBoxHandler()
      }
    })
    currInteraction.on('boxend', () => {
      try {
        const extent = currInteraction.getGeometry().getExtent()
        if (defaultOpt && typeof defaultOpt.endDragBoxHandler === 'function') {
          defaultOpt.endDragBoxHandler(extent)
        }
      } catch (ex) {
        return
      }
    })
    // 当isCancel值为true时，框选的boxend事件将会禁用
    // this.isCancel = false;
    return currInteraction
  }

  getInteractionById(interactionId) {
    for (const index in this.interactionCollection) {
      if (this.interactionCollection[index].id === interactionId) {
        return this.interactionCollection[index]
      }
    }
    return null
  }

  createInteraction(opt) {
    let objTemp = {}
    if (typeof opt === 'string') {
      objTemp.id = opt
    } else if (opt && opt instanceof Object) {
      objTemp = opt
      if (!objTemp.hasOwnProperty('id')) {
        throw new Error('interaction对象构造函数参数需要id属性')
      }
    } else {
      throw new Error('create方法提供的参数只能是字符串或对象')
    }
    let interaction = this.getInteractionById(objTemp.id)
    if (!interaction) {
      if (objTemp.type === 'dragBox') {
        interaction = this.dragBoxInteraction(objTemp)
      } else {
        interaction = this.selectInteraction(objTemp)
      }
      this.interactionCollection.push({ id: objTemp.id, itr: interaction })
    }
    return interaction
  }

  removeInteraction(interactionId) {
    const interaction = this.getInteractionById(interactionId)
    if (interaction) {
      this.map.removeInteraction(interaction.itr)
      this.interactionCollection.pop(interaction)
    }
  }

  // 事件注册 end

  /*
  MapTuYuanHelper.prototype.featureRequest = function (options) {

      var layers = [];
      if (options.layers && options.layers.length > 0)
      {
          layers = options.layers;
      }
      else if (options.layer)
      {
          layers.push(options.layer);
      }

      var featureRequest = new ol.format.WFS().writeGetFeature({
          srsName: this.proj,
          featureNS: 'http://www.wz.gov.cn/',
          featurePrefix: 'wzmap',
          featureTypes: layers,
          outputFormat: 'application/json',
          filter: ol.format.filter.like('Name', '*中邦*')
          //    ol.format.filter.and(
          //  ol.format.filter.like('name', 'Mississippi*'),
          //  ol.format.filter.equalTo('waterway', 'riverbank')
          //)
      });

      // then post the request and add the received features to a layer
      fetch('http://121.42.53.142:8080/geoserver/wzmap/ows?service=wfs', {
          method: 'POST',
          body: new XMLSerializer().serializeToString(featureRequest)
      }).then(function (response) {
          return response.json();
      }).then(function (json) {
          if (typeof (options.callback) == "function") {
              var features = new ol.format.GeoJSON().readFeatures(json);
              options.callback(features, options.layer);
          }
          //
          //vectorSource.addFeatures(features);
          //map.getView().fit(vectorSource.getExtent(), (map.getSize()));
      });
  }*/
  partSearch(options, callback) {
    const layers = options.partId
    const CQL_FILTER = 'cql_filter=Within(THE_GEOM,POLYGON((' + options.bnd.MinX + ' ' + options.bnd.MinY +
      ',' + options.bnd.MaxX + ' ' + options.bnd.MinY +
      ',' + options.bnd.MaxX + ' ' + options.bnd.MaxY +
      ',' + options.bnd.MinX + ' ' + options.bnd.MaxY +
      ',' + options.bnd.MinX + ' ' + options.bnd.MinY + ')))'
    this.mapUnAgentSearch({
      layer: layers,
      CQL_FILTER: CQL_FILTER,
      callback: callback
    })
    // this.mapSearch({ layer: layers, CQL_FILTER: CQL_FILTER, callback: callback });
  }

  mapSearchJoson(options, callback) {
    if (options.layerId) {
      const layerName = this.getLayerName(options.layerId).toUpperCase()
      const CQL_FILTER = 'CQL_FILTER=' + options.key + "='" + options.value + "'"
      this.mapUnAgentSearch({
        layer: layerName,
        maxSize: options.maxSize,
        CQL_FILTER: CQL_FILTER,
        callback: callback
      })
      // this.mapSearch({ layer: layerName, maxSize: options.maxSize, CQL_FILTER: CQL_FILTER, callback: callback });
    }
  }

  /* // 获取百度行政区划，当可以访问外网或者存在代理
  getBaiduAdministrationArea(name, callback) {
    var bdary = new BMap.Boundary()
    // 获取行政区域
    bdary.get(name, function(rs) {
      if (rs) {
        callback(rs.boundaries[0])
      }
    })
  }*/

  // 行政区划遮罩层---
  /* addAdministrationArea(rs, name, callback) {
    // 获取rgb类型的颜色  IE7不支持
    function randomColor() {
      const r = Math.floor(Math.random() * 256)
      const g = Math.floor(Math.random() * 256)
      const b = Math.floor(Math.random() * 256)
      return 'rgba(' + r + ',' + g + ',' + b + ',0.3)'
    }
    const style = new Style({
      // //填充色
      fill: new Fill({
        color: randomColor()
      })
      // 边框色
      // stroke: new ol.style.Stroke({
      //    width: 4,
      //    color: '#' + Math.floor(16777216 * Math.random()).toString(16)
      // })
    })
    let strs = new Array()
    strs = rs.split(';')
    var s = []
    for (var i = 0; i < strs.length; i++) {
      var baiduMKT = coordtransform.bd_wgs2bd_mkt(strs[i].split(',')[0], strs[i].split(',')[1])
      s.push(baiduMKT)
    }
    var feature = new ol.Feature({
      geometry: new ol.geom.Polygon([s])
    })
    feature.setStyle(style)
    createMaskOverlay.addFeature(feature)
    oCutePolygon.addPolygon(feature)// 调用切割方法
    oCutePolygon.initFocusFeatures()
    callback(feature, name)
  }*/

  // 图层查询 end

  // overlay begin
  // MapTuYuanHelper.prototype.clearOverlay = function () {
  //    this.map.clearOverlays();
  // }

  removeOverlays(lays) {
    if (lays !== undefined) {
      for (const index in lays) {
        this.map.removeOverlay(lays[index])
      }
    }
  }

  cleartPartOverlays() {
    for (const index in this.partOverlaysList) {
      this.map.removeOverlay(this.partOverlaysList[index])
    }
    this.partOverlaysList.slice(0, this.partOverlaysList.length)
  }
  // overlay end

  // ---
  /* createMaskLayer(p) {
    var strs = new Array()
    strs = p.split(';')
    // 4.添加环形遮罩层

    // 5. 给目标行政区划添加边框，其实就是给目标行政区划添加一个没有填充物的遮罩层
    var style = new ol.style.Style({
      // //填充色
      // fill: new ol.style.Fill(
      //    {
      //        color: [0xff, 0x00, 0xff, 0.1]//'rgba(212, 255, 249, 0.3)'
      //    }),
      // 边框色
      stroke: new ol.style.Stroke({
        width: 6,
        color: '#FFFF00'
      })
    })
    var s = []
    for (var i = 0; i < strs.length; i++) {
      var pointGcj02 = coordtransform.bd09togcj02(strs[i].split(',')[0], strs[i].split(',')[1])// 火星坐标系
      var wgs84 = coordtransform.gcj02towgs84(pointGcj02[0], pointGcj02[1])// 84坐标系
      s.push(wgs84)
    }
    var feature = new ol.Feature({
      geometry: new ol.geom.Polygon([s])
    })
    feature.setId('Polygon')
    feature.setStyle(style)
    createMaskOverlay.addFeature(feature)
  }*/

  getMinMaxXY = function() {
    const view = this.map.getView().calculateExtent(this.map.getSize())
    return {
      xMin: view[0],
      yMin: view[1],
      xMax: view[2],
      yMax: view[3]
    }
  }

  centerAndZoom(p, zoom) {
    this.map.centerAndZoom(p, zoom)
  }

  addEventListener(key, callBack) {
    this.map.addEventListener(key, callBack)
  }

  removeEventListener(key, callBack) {
    this.map.removeEventListener(key, callBack)
  }

  /* setSelectFeatures(features) {
    if (features.length !== 0) {
      if (this.isMultiSelect) {
        let flag = true
        this.selectedFeatures.forEach((item) => {
          if (item.feature === features[0]) {
            flag = false
            return
          }
        })
        if (flag) {
          this.selectedFeatures.push({ feature: features[0], style: features[0].getStyle() })
          this.selectedFeature = { feature: features[0], style: features[0].getStyle() }
          features[0].setStyle(this.selectedStyle)
        }
      } else {
        if (this.selectedFeature) {
          this.selectedFeature.feature.setStyle(this.selectedFeature.style)
        }
        this.selectedFeatures = [{ feature: features[0], style: features[0].getStyle() }]
        this.selectedFeature = { feature: features[0], style: features[0].getStyle() }
        features[0].setStyle(this.selectedStyle)
      }
    } else {
      this.selectedFeatures.forEach((item) => {
        item.feature.setStyle(this.selectedFeature.style)
      })
      this.selectedFeatures = []
      this.selectedFeature = null
    }
  }*/

  /*
   轨迹播放
  startPlayTrace = function(obj) {
    window.traceIndex = 0
    window.isPause = false
    window.playMarker = obj.marker
    if (window.playIntervalHandler != null) {
      window.clearInterval(window.playIntervalHandler)
    }
    var path = obj.path[window.traceIndex]
    var evtPois
    if (obj.evtMarker) {
      evtPois = obj.evtMarker[window.traceIndex]
    }
    obj.index += 1
    window.playIntervalHandler = window.setInterval(function() {
      mapHelper.playTrace(obj, path, evtPois, obj.playEndCallback)
    }, obj.interval)
  }

  MapTuYuanHelper.prototype.playTrace = function(obj, path, evtPois, callback) {
    if (window.traceIndex < path.length && !window.isPause) {
      var poi = path[window.traceIndex]
      if (window.traceIndex > 0) {
        mapHelper.Polyline([path[window.traceIndex - 1], poi])
      }
      if (window.playMarker != null) {
        if (evtPois) {
          $(evtPois).each(function() {
            if (map.getDistance(poi, this.getPosition()).toFixed(2) < 200) {
              TyMap.getMap().addOverlay(this)
              evtPois.pop(this)
              return
            }
          })
        }
        window.playMarker.setPosition(poi)
        if (obj.autoView) {
          mapHelper.map.setCenter(path[window.traceIndex])
        }
        if (obj.Rotation && window.traceIndex < path.length - 1) {
          mapHelper.setRotation(window.playMarker, poi, path[window.traceIndex + 1])
        }
      }
      window.traceIndex = window.traceIndex + 1
    }
    if (window.traceIndex == path.length) {
      window.clearInterval(window.playIntervalHandler)
      if (typeof (callback) === 'function') {
        callback(obj)
      }
    }
  }

  // 轨迹播放
  MapTuYuanHelper.prototype.stopPlayTrace = function() {
    window.traceIndex = 0
    window.isPause = false
    window.playMarker = null
    if (window.playIntervalHandler != null) {
      window.clearInterval(window.playIntervalHandler)
    }
  }*/

  // 多边形闪烁
  flashPolygon(polygon, text) {
    let delay = 0
    for (let flashTimes = 0; flashTimes < 10; flashTimes++) {
      delay += 200
      setTimeout(() => {
        polygon.setStyle(this.getLayerStyle(0.1, text))
      }, delay)
      delay += 200
      setTimeout(() => {
        polygon.setStyle(this.getLayerStyle(0.5, text))
      }, delay)
    }
  }

  setRotation(marker, curPos, targetPos) {
    let deg = 0
    // start!
    curPos = this.map.pointToPixel(curPos)
    targetPos = this.map.pointToPixel(targetPos)
    if (targetPos.x !== curPos.x) {
      const tan = (targetPos.y - curPos.y) / (targetPos.x - curPos.x)
      const atan = Math.atan(tan)
      deg = atan * 360 / (2 * Math.PI)
      // degree  correction;
      if (targetPos.x < curPos.x) {
        deg = -deg + 90 + 90
      } else {
        deg = -deg
      }
      marker.setRotation(-deg)
    } else {
      let bias = 0
      if (targetPos.y - curPos.y > 0) {
        bias = -1
      } else {
        bias = 1
      }
      marker.setRotation(-bias * 90)
    }
    return
  }

  panTo = function(pt) {
    this.map.panTo(pt)
  }

  removeTileLayers(titleLayers) {
    if (typeof (titleLayers) === 'object') {
      for (const index in titleLayers) {
        if (index < titleLayers.length) {
          this.map.removeTileLayer(titleLayers[index])
        }
      }
    }
  }

  reset() {
    this.map.reset()
  }
}

export default TyHelper
/*
var mapHelper = new MapTuYuanHelper()

function VectorLayer(opt) {
  var _opt = {
    style: undefined
  }
  if (opt && $.isPlainObject(opt)) { $.extend(true, _opt, opt) }
  this.vectorLayer = new ol.layer.Vector({
    source: new ol.source.Vector({ wrapX: false, features: _opt.features }),
    style: _opt.style
  })
  this.vectorLayerSource = this.vectorLayer.getSource()
  mapHelper.getMap().addLayer(this.vectorLayer)
}
VectorLayer.prototype = {
  addFeature: function(feature) {
    this.vectorLayerSource.addFeature(feature)
  },
  addFeatures: function(features) {
    this.vectorLayerSource.addFeatures(features)
  },
  // 将集合中指定的VectorOverlay的对象进行移除
  removeFeature: function(feature) {
    this.vectorLayerSource.removeFeature(feature)
  },
  clear: function() {
    this.vectorLayerSource.clear()
  },
  // 通过指定ID查找对应的Feature对象
  getFeatureById: function(id) {
    return this.vectorLayerSource.getFeatureById(id)
  },
  getFeatureByFieldValue: function(field, value) {
    var feature, obj
    var features = this.vectorLayerSource.getFeatures()
    for (var i = 0; i < features.length; i++) {
      obj = features[i].getProperties()
      if (obj[field] == value) {
        feature = features[i]
        break
      }
    }
    return feature
  },
  // 获取所有的VectorOverlay对象
  getFeatures: function() {
    this.vectorLayerSource.getFeatures()
  },
  // 解除矢量图层与地图的关联
  dispose: function() {
    mapHelper.getMap().removeLayer(this.vectorLayer)
  }
}
*/

